<!-- 评论 -->
<template>
    <!-- 用户评论 -->
    <div class="submit-comment">
        <MdEditor v-model="userComment.content" placeholder="在这里留下你的评论吧..." :toolbars="editorTool" :footers="[]"
            :preview="false" class="comment-editor" :tabWidth="4" />
        <el-tooltip :disabled="userComment.content.length !== 0" content="请先输入内容" placement="top" width="100">
            <div>
                <el-button @click="showPreview()" :disabled="userComment.content.length === 0"
                    style="margin: 10px 18px 10px 350px">预览</el-button>
                <el-button @click="submitComment()" type="primary" :disabled="userComment.content.length === 0"
                    style="margin: 10px">提交</el-button>
            </div>
        </el-tooltip>
    </div>

    <!-- 评论预览 -->
    <el-drawer v-model="previewIsShow" direction="rtl" size="40%">
        <template #header="{ header }">
            <h1 :id="header" style="font-size: 24px;">评论预览</h1>
        </template>
        <MdPreview v-model="userComment.content" />
    </el-drawer>

    <!-- 评论区 -->
    <template v-if="isNull">
        <el-empty description="还没有人评论呢~" />
    </template>
    <template v-else>
        <div v-infinite-scroll="loadComments" :infinite-scroll-disabled="disabled">
            <el-card style="width: 95%; margin-bottom: 30px;" shadow="hover" v-for="item in commentList" :key="item.id">
                <template #header>
                    <div class="comment-header">
                        <el-avatar :size="27" :src="item.user_avatar" :key="item.user_avatar" />
                        <span class="username">{{ item.username }}</span>
                        <span class="date">{{ item.create_date }}</span>
                    </div>
                </template>
                <div class="comment-body">
                    <MdPreview v-model="item.content" />
                </div>
            </el-card>
            <p v-if="noMore" style="text-align: center; color: #909399;">没有更多评论了哦~</p>
        </div>
    </template>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useProblemStore } from '@/stores/problem'
import { addCommentAPI, getCommentListAPI } from '@/apis/comment'
import { ElMessage, ElMessageBox } from 'element-plus'
import { MdEditor, MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import { useUserStore } from '@/stores/user'
import { useRouter, useRoute } from 'vue-router'

onMounted(() => {
    if (sessionStorage.getItem('userCommentContent')) {
        userComment.value.content = sessionStorage.getItem('userCommentContent')
    }
})

const router = useRouter()
const route = useRoute()
const problemStore = useProblemStore()
const userStore = useUserStore()
const commentList = ref([])

const previewIsShow = ref(false)

// 用户评论
const userComment = ref({
    userId: userStore.userInfo.id,
    problemId: problemStore.problem.id,
    content: "",
})

const editorTool = [
    'bold',
    'underline',
    'italic',
    '=',
    'code'
]

const isNull = ref(false)

const disabled = computed(() => noMore.value)
const noMore = computed(() => reqData.value.isMax)

const reqData = ref({
    page: 1,
    pageFiled: problemStore.problem.title_en,
    isMax: false
})

// 点击预览
const showPreview = () => {
    previewIsShow.value = true
}

// 提交评论
const submitComment = () => {
    // 先检查是否登录
    if (userStore.userInfo.token.length === 0) {
        // 没有登录
        ElMessageBox.confirm(
            '登录后才能提交评论哦~',
            '提示',
            {
                distinguishCancelAndClose: true,
                confirmButtonText: '登录', // 跳转登录
                cancelButtonText: '取消',  // 取消跳转
            }
        ).then(() => {
            // 保存用户评论内容，跳转登录
            // 先保存重定向地址
            sessionStorage.setItem('redirectPath', route.fullPath)
            sessionStorage.setItem('userCommentContent', userComment.value.content)
            router.push('/login')
        }).catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消'
            })
        })
    } else {
        // http请求携带token
        const problem_id = problemStore.problem.id
        const content = userComment.value.content
        addCommentAPI('/problem/addcomment', { problem_id, content }).then((res) => {
            if (res.code === 0) {
                ElMessage({
                    type: 'success',
                    message: '评论成功'
                })
                // 延迟一段时间后页面刷新
                setTimeout(() => {
                    // 清除评论缓存
                    sessionStorage.removeItem('userCommentContent');
                    // 刷新页面
                    window.location.reload();
                }, 1000);
            }
        }).catch((Error) => {
            ElMessage({
                type: 'error',
                message: Error
            })
        })
    }
}


// 加载评论
const loadComments = async () => {
    try {
        const res = await getCommentListAPI(`/problem/${problemStore.problem.id}/commentlist?page=${reqData.value.page}`)
        if (res.code === 0) {
            if (reqData.value.page === 1 && res.comments.length === 0) {
                // 第一次加载为空
                isNull.value = true
            }
            if (!res.has_more_comments) {
                // 没有更多评论
                commentList.value.push(...res.comments)
                reqData.value.isMax = true

            } else {
                commentList.value.push(...res.comments)
                reqData.value.page = res.next_page
            }
        }
    } catch (error) {
        ElMessage({ type: "error", message: "获取评论失败" })
    }
}
</script>

<style scoped lang="scss">
.comment-header {
    display: flex;
    justify-content: start;
}

.username {
    display: block;
    width: 250px;
    line-height: 27px;
    margin-left: 15px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.date {
    display: block;
    line-height: 27px;
    margin-left: 15px;
    color: #8e8e8e;
}

.submit-comment {
    margin-bottom: 30px;
}

.comment-editor {
    width: 95%;
    height: 170px;
    border-radius: 5px;
}
</style>